package com.app.Activity;

import it.unipr.ce.dsg.s2p.sip.Address;

import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.app.Controller.NetworkController;
import com.app.Controller.ReadWriteFileController;
import com.app.Network.PingThread;
import com.app.Tree.BoardView;
import com.app.Tree.INode;
import com.app.Tree.TextNode;
import com.app.Tree.TreeNode;

import ReadWriteXML.CMember;
import ReadWriteXML.ReadXML;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class frmMatKetNoiActivity extends Activity{
	public static Runnable raVersion = null;
	public static boolean isShowed=false;
	public static Runnable raClose;
	Button btnKetNoiLai;
	TextView txtKetNoiLai;
	ArrayList<CMember> memberListGroup;
	int soLan=0;
	public long version;
	public static TreeNode nodeAdd;
	public static String NodeString;
	public static String DelNodeString;
	private static TreeNode treenode;
	private static TextNode textnode;
	private static ArrayList<Address> Iponline ;
	private static ArrayList<String> versionList ;
	public  static  long vsMax;
	public void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_mat_ket_noi);
		isShowed=true;
		raClose=new Runnable() {
			
			@Override
			public void run() {
				close();
			}
		};
		raVersion=new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
			}
		};
		soLan=0;
		
		txtKetNoiLai=(TextView)findViewById(R.id.txtKetNoiLai);
		btnKetNoiLai=(Button)findViewById(R.id.btnKetNoiLai);		
		btnKetNoiLai.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				PingThread pingThread=new PingThread("ReConnect");
				pingThread.start();
				 Iponline = new ArrayList<Address>();
				 versionList = new ArrayList<String>();
				final ProgressDialog dialog = ProgressDialog.show(frmMatKetNoiActivity.this, "", 
                        "Đang kết nối. Vui lòng chờ...", true);
				
				memberListGroup = ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
//				for (CMember member : memberListGroup) {					
//					if(member.get_ip().equals(NetworkController._peer.getAddressPeer()))
//					{
//						//Log.d("PingThread","Run() - if ( " + member.get_ip().equals(NetworkController._peer.getAddressPeer()) + " )");
//					}
//					else
//					{
//						NetworkController.sendPing(new Address(member.get_ip()));
//					}
//				}
				//NetworkController.sendPing(new Address(NetworkController.thanhLapNhomIP));
				CountDownTimer count=new CountDownTimer(10000,1000) {
					
					@Override
					public void onTick(long millisUntilFinished) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void onFinish() {						
						if(NetworkController.getStated()){
							
//							for(Address ip : Iponline){
//								NetworkController.sendGetVersion(new Address(ip));
//							}

							for (CMember member : memberListGroup) {					
								if(!member.get_userName().equals(NetworkController._peer.account.get_Username()))
								{
									NetworkController.sendGetVersion(new Address(member.get_ip()));
								}
								
							}
							
							
//							Log.d("An", "truoc countdown: ");
							dialog.setTitle("Đang đồng bộ dữ liệu");
							CountDownTimer count1=new CountDownTimer(10000,1000){
								
								@Override
								public void onTick(long millisUntilFinished) {
									
								}
								
								@Override
								public void onFinish() {
									
									String versionmax = versionMax(versionList);
									String[] s = versionmax.split("/");
									 vsMax =Long.parseLong(s[0]);
									String adSender = s[1];
									Log.d("An", "frmmatketnoi-versionmax"+vsMax+"-"+adSender);
									long myversion = ReadWriteFileController.getVersionTree();
									Log.d("An", "frmmatketnoi-myversion: "+myversion);
									
									if(myversion < vsMax){
										Log.d("An", "frmmatketnoi-myversion < vs: ");
										NetworkController.sendVersionTree(adSender, myversion);
									}
									
									close();
								}								
							};
							count1.start();
							//close();
							
						}else{
							dialog.dismiss();
							setTextBox();	
							
						}
//						t.setRunning(false);
						Log.d("Phu","cound down finish");
					}
				};
				count.start();
			}
		});
	}
	@Override
	public void onStop(){
		super.onStop();
		isShowed=false;
	}
	public void close(){
		isShowed=false;
		finish();
	}
	private void setTextBox(){
		soLan++;
		txtKetNoiLai.setText("Kết nối lại lần thứ "+soLan+" thất bại!");
	}
	public static void addVersion(String s){
		Log.d("An", "frmmatketnoi-addVersion: " +s);
		versionList.add(s);
	}
	
	public static String versionMax(ArrayList<String> listversion){
		String s = null ;
		long vs = 0;
		String address = null;
		for(String lvs : listversion){
			String[] sp = lvs.split("#");
			long ver = Long.parseLong(sp[0]);
			String dress = sp[1];
			if(ver > vs){
				vs = ver;
				address = dress;
			}
				
		}
		s = vs+"/"+address;
		Log.d("An", "frmmatketnoi-versionMax: " +s);
		return s;
	}
	
	public void readXml(String path){
		Document doc=ReadXML.BuildXML(path);
		treenode=new TreeNode();
		treenode.readXML((Element)doc.getFirstChild().getFirstChild());
	}
	
	public void writeDeleteXML(String path, long id, long vs){
		treenode.writeDeletedXML(path, id, vs);
		Log.d("Phu","frmmatketnoi-writeXML: Da ghi cay xuong file:"+path);
	}
	
	public void writeXML(String path){
		treenode.writeXML(path);
		Log.d("Phu","frmmatketnoi-.writeXML: Da ghi cay xuong file:"+path);
	}
	
	public void parseWriteDelXML(String delnode){		
		String[] s = delnode.split("#");
		String[] detail = null; 		
		for(String i : s){			
			detail = i.split("/");
			long id = Long.parseLong(detail[0]);
			long ver = Long.parseLong(detail[1]);			
			treenode.deleteNode(id);
			writeDeleteXML(ReadWriteFileController.DeletedNodesPath, id, ver);
		}
	}
	
	public long versionMaxInDelXml(String delnode){
		long ver = 0;
		String[] s = delnode.split("#");
		String[] detail = null; 
		for(String i : s){
			detail = i.split("/");
			long vs = Long.parseLong(detail[1]);
			if(vs > ver)
				ver = vs;
		}
		return ver;
	}
	public static void addIP(Address ip){
		Log.d("An", "frmmatketnoi-ipOnline: "+ ip);
		Iponline.add(ip);
	}

	public static ArrayList<Address> getIponline() {
		return Iponline;
	}

	public static void setIponline(ArrayList<Address> iponline) {
		Iponline = iponline;
	}
	
	public static void dongBo(String s,String delnode){
		TreeNode currentTree=new TreeNode();
		currentTree.readXml(BoardView.treePath);
		Log.d("An", "frmmatketnoi-dongBo....s: " + s + ", delnode=" + (delnode==null) + (delnode==""));
		//del node
		if(delnode != ""){
			String[] sDel = delnode.split("#");
			String[] detail; 		
			for(String i : sDel){			
				detail = i.split("/");
				long id = Long.parseLong(detail[0]);
				long ver = Long.parseLong(detail[1]);			
				Log.d("An","frmmatketnoi-dongBo....delete-id= "+id+", vs="+ver);
				INode del = currentTree.getById(id);
				currentTree.remove(del);		
				currentTree.writeDeletedXML(ReadWriteFileController.DeletedNodesPath, id, ver);			
			}
		}
		//add & update node
		String[] ns = s.split("/");
		Log.d("An", "frmmatketnoi-dongBo....ns: " + ns[0] + ns.length);
		for(int i=0; i<ns.length; i++){
			ArrayList<INode> lst = currentTree.getListNode();
			Log.d("An", "frmmatketnoi-dongBo.... listnode= " + (lst==null) + ", size= " + lst.size());
			INode iNode = new TreeNode();
			iNode.parse(ns[i]);
			Log.d("An", "frmmatketnoi-dongBo.... label: " + iNode.getLabel());
			if(iNode.getLabel() == 0){
				Log.d("An", "frmmatketnoi-dongBo.... thêm node moi: " + iNode.getTitle()+" - "+iNode.getId()+", pID: "+ iNode.getParentID());
				INode p = currentTree.getById(iNode.getParentID());
				Log.d("An", "frmmatketnoi-dongBo.... node cha: " + p.getTitle() + "id= " + p.getId());
				if(p!=null){
					p.add(iNode);					
					Log.d("An", "frmmatketnoi-dongBo....add node: " +iNode.getTitle()+" vao node " + p.getTitle());
				}
			}else{
				Log.d("An", "frmatketnoi-dongBo.... cap nhat node: " );
				INode c = currentTree.getById(iNode.getId());
				c.setTitle(iNode.getTitle());
				c.setText(iNode.getText());
				c.setVersion(iNode.getVersion());
				c.setLabel(iNode.getLabel());					
			}
		}
		
		currentTree.setVersion(vsMax);
		currentTree.writeXML(ReadWriteFileController.TREE_PATH);
		Log.d("An", "frmatketnoi-dongBo.... hết dongbo: " );
	}	
}
